package com.heisen.gateway.filter;


import org.apache.commons.lang.StringUtils;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import reactor.core.publisher.Mono;


import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;


//response包装类
public class HttpResponseDecorator extends ServerHttpResponseDecorator {

    private String proxyUrl;

    private ServerHttpRequest request;


    /**
     * 构造函数
     *
     * @param delegate
     */
    public HttpResponseDecorator(ServerHttpRequest request, ServerHttpResponse delegate, String proxyUrl) {
        super(delegate);
        this.request = request;
        this.proxyUrl = proxyUrl;
    }


    @Override
    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
        HttpStatus status = this.getStatusCode();
        if(status.equals(HttpStatus.FOUND)){
            String domain = "";
            if(StringUtils.isBlank(proxyUrl)) {
                domain = request.getURI().getScheme()+"://"+request.getURI().getAuthority()+"/uua";
            } else {
                domain = proxyUrl + "/uua";
            }
            String location = getHeaders().getFirst("Location");
            String replaceLocation = location.replaceAll("^((ht|f)tps?):\\/\\/(\\d{1,3}.){3}\\d{1,3}(:\\d+)?",domain);
            getHeaders().set("Location",replaceLocation);
            System.out.println("--------------Location---------------------");
            System.out.println(replaceLocation);
        }
        this.getStatusCode();
        return super.writeWith(body);
    }

}
